/* 订单页面逻辑 */
class OrdersManager {
    constructor() {
        this.orders = [];
        this.currentFilter = 'all';
        this.init();
    }

    init() {
        this.bindEvents();
        this.loadOrders();
        // 每30秒自动刷新订单列表，以显示最新的订单状态
        setInterval(() => {
            if (window.authManager && window.authManager.isAuthenticated()) {
                this.loadOrders();
            }
        }, 30000); // 30秒刷新一次
    }

    bindEvents() {
        // 筛选按钮
        document.querySelectorAll('.filter-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                this.filterOrders(e.target.dataset.status);
            });
        });

        // 订单详情模态框
        document.getElementById('closeOrderDetail').addEventListener('click', () => {
            this.hideOrderDetail();
        });

        // 点击模态框外部关闭
        document.getElementById('orderDetailModal').addEventListener('click', (e) => {
            if (e.target.id === 'orderDetailModal') {
                this.hideOrderDetail();
            }
        });
    }

    async loadOrders() {
        try {
            this.showLoading(true);
            
            // 检查用户认证状态
            const isAuthenticated = window.authManager ? window.authManager.isAuthenticated() : false;
            const currentUser = window.authManager ? window.authManager.getCurrentUser() : null;
            
            console.log('加载订单 - 认证状态:', isAuthenticated);
            console.log('加载订单 - 当前用户:', currentUser);
            
            if (!isAuthenticated) {
                this.showNotification('请先登录 / Please login first', 'error');
                this.showEmptyState();
                return;
            }
            
            const result = await window.api.getOrders();
            console.log('订单API响应:', result);
            
            if (result.success) {
                this.orders = result.data.orders || [];
                console.log('加载到的订单:', this.orders);
                this.renderOrders();
            } else {
                console.error('订单API返回错误:', result.error);
                this.showNotification('加载订单失败: ' + result.error, 'error');
                this.showEmptyState();
            }
        } catch (error) {
            console.error('加载订单失败:', error);
            this.showNotification('加载订单失败: ' + error.message, 'error');
            this.showEmptyState();
        } finally {
            this.showLoading(false);
        }
    }

    renderOrders() {
        const ordersList = document.getElementById('ordersList');
        const emptyOrders = document.getElementById('emptyOrders');
        
        if (this.orders.length === 0) {
            this.showEmptyState();
            return;
        }

        // 根据筛选条件过滤订单
        let filteredOrders = this.orders;
        if (this.currentFilter !== 'all') {
            filteredOrders = this.orders.filter(order => order.status === this.currentFilter);
        }

        if (filteredOrders.length === 0) {
            this.showEmptyState();
            return;
        }

        // 按创建时间倒序排列
        filteredOrders.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));

        ordersList.innerHTML = filteredOrders.map(order => this.renderOrderItem(order)).join('');
        emptyOrders.style.display = 'none';
    }

    renderOrderItem(order) {
        const statusText = this.getStatusText(order.status);
        const statusClass = this.getStatusClass(order.status);
        const createdDate = new Date(order.created_at).toLocaleDateString();
        
        return `
            <div class="order-item">
                <div class="order-header">
                    <div class="order-info">
                        <span class="order-number">订单号: ${order.order_number}</span>
                        <span class="order-date">${createdDate}</span>
                        ${order.logistics && order.logistics.distance_km ? `
                            <span class="order-distance">
                                <i class="fas fa-route"></i> 配送距离: ${typeof order.logistics.distance_km === 'number' ? order.logistics.distance_km.toFixed(2) : order.logistics.distance_km} 公里
                            </span>
                        ` : ''}
                    </div>
                    <div class="order-status">
                        <span class="status ${statusClass}">${statusText}</span>
                    </div>
                </div>
                
                <div class="order-items">
                    ${order.items.map(item => `
                        <div class="order-item-product">
                            <div class="product-image">
                                <img src="https://via.placeholder.com/60x60?text=${encodeURIComponent(item.product_name)}" 
                                     alt="${item.product_name}"
                                     onerror="this.src='https://via.placeholder.com/60x60?text=商品图片'">
                            </div>
                            <div class="product-info">
                                <h4 class="product-name">${item.product_name}</h4>
                                <div class="product-specs">
                                    <span class="spec">数量: ${item.quantity}</span>
                                    <span class="spec">单价: ¥${item.price.toFixed(2)}</span>
                                </div>
                            </div>
                            <div class="product-total">
                                <span class="total-price">¥${(item.price * item.quantity).toFixed(2)}</span>
                            </div>
                        </div>
                    `).join('')}
                </div>
                
                <div class="order-footer">
                    <div class="order-total">
                        <span class="total-label">订单总额:</span>
                        <span class="total-amount">¥${order.total_amount.toFixed(2)}</span>
                    </div>
                    <div class="order-actions">
                        <button class="btn btn-outline" onclick="ordersManager.viewOrderDetail('${order.order_number}')">
                            查看详情
                        </button>
                        ${this.getActionButtons(order)}
                    </div>
                </div>
            </div>
        `;
    }

    getActionButtons(order) {
        const buttons = [];
        
        switch (order.status) {
            case 'Shipped':
                buttons.push(`<button class="btn btn-primary" onclick="ordersManager.confirmDelivery('${order.order_number}')">确认收货</button>`);
                break;
            case 'Delivered':
                buttons.push(`<button class="btn btn-outline" onclick="ordersManager.reorder('${order.order_number}')">再次购买</button>`);
                break;
        }
        
        return buttons.join('');
    }

    getStatusText(status) {
        const statusMap = {
            'Processing': '待处理 / Processing',
            'Shipped': '已发货 / Shipped',
            'Delivered': '已送达 / Delivered'
        };
        return statusMap[status] || status;
    }

    getStatusClass(status) {
        const classMap = {
            'Processing': 'status-processing',
            'Shipped': 'status-shipped',
            'Delivered': 'status-delivered'
        };
        return classMap[status] || '';
    }

    filterOrders(status) {
        this.currentFilter = status;
        
        // 更新按钮状态
        document.querySelectorAll('.filter-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        document.querySelector(`[data-status="${status}"]`).classList.add('active');
        
        this.renderOrders();
    }

    async viewOrderDetail(orderNumber) {
        try {
            const result = await window.api.getOrderDetail(orderNumber);
            
            if (result.success) {
                this.showOrderDetail(result.data);
            } else {
                this.showNotification('获取订单详情失败: ' + result.error, 'error');
            }
        } catch (error) {
            console.error('获取订单详情失败:', error);
            this.showNotification('获取订单详情失败: ' + error.message, 'error');
        }
    }

    showOrderDetail(order) {
        const modal = document.getElementById('orderDetailModal');
        const content = document.getElementById('orderDetailContent');
        
        const createdDate = new Date(order.created_at).toLocaleString();
        const deliveryDate = new Date(order.estimated_delivery * 1000).toLocaleDateString();
        
        content.innerHTML = `
            <div class="order-detail">
                <div class="detail-section">
                    <h3>订单信息</h3>
                    <div class="detail-row">
                        <span class="label">订单号:</span>
                        <span class="value">${order.order_number}</span>
                    </div>
                    <div class="detail-row">
                        <span class="label">订单状态:</span>
                        <span class="value status ${this.getStatusClass(order.status)}">${this.getStatusText(order.status)}</span>
                    </div>
                    <div class="detail-row">
                        <span class="label">创建时间:</span>
                        <span class="value">${createdDate}</span>
                    </div>
                    <div class="detail-row">
                        <span class="label">预计送达:</span>
                        <span class="value">${deliveryDate}</span>
                    </div>
                </div>
                
                <div class="detail-section">
                    <h3>收货地址</h3>
                    <div class="address-info">
                        <p><strong>${order.shipping_address.name}</strong> ${order.shipping_address.phone}</p>
                        <p>${order.shipping_address.address}</p>
                    </div>
                </div>
                
                    <div class="detail-section">
                        <h3>订单操作</h3>
                        <div class="order-actions-detail">
                            ${order.status === 'Delivered' ? `
                                <button class="btn btn-primary" onclick="ordersManager.showReviewModal('${order.order_number}')">
                                    <i class="fas fa-star"></i> 评价商品
                                </button>
                            ` : ''}
                        </div>
                    </div>
                
                ${order.logistics ? `
                <div class="detail-section">
                    <h3>物流信息</h3>
                    <div class="logistics-info">
                        ${order.logistics.distance_km ? `
                            <div class="logistics-row">
                                <span class="label"><i class="fas fa-route"></i> 配送距离:</span>
                                <span class="value">${typeof order.logistics.distance_km === 'number' ? order.logistics.distance_km.toFixed(2) : order.logistics.distance_km} 公里</span>
                            </div>
                        ` : ''}
                        ${order.logistics.duration_h ? `
                            <div class="logistics-row">
                                <span class="label"><i class="fas fa-clock"></i> 预计配送时间:</span>
                                <span class="value">${typeof order.logistics.duration_h === 'number' ? order.logistics.duration_h.toFixed(1) : order.logistics.duration_h} 小时</span>
                            </div>
                        ` : ''}
                        ${order.logistics.warehouse_address ? `
                            <div class="logistics-row">
                                <span class="label"><i class="fas fa-warehouse"></i> 主发货地:</span>
                                <span class="value">${order.logistics.warehouse_address}</span>
                            </div>
                        ` : ''}
                        ${order.logistics.origin_addresses && order.logistics.origin_addresses.length > 1 ? `
                            <div class="logistics-row">
                                <span class="label"><i class="fas fa-map-marker-alt"></i> 发货地数量:</span>
                                <span class="value">${order.logistics.origin_count || order.logistics.origin_addresses.length} 个</span>
                            </div>
                            <div class="logistics-row">
                                <span class="label"><i class="fas fa-list"></i> 所有发货地:</span>
                                <span class="value logistics-addresses">
                                    ${order.logistics.origin_addresses.map((addr, idx) => `
                                        <div style="margin-top: ${idx > 0 ? '5px' : '0'}; font-size: 12px; color: #666;">
                                            ${idx + 1}. ${addr}
                                        </div>
                                    `).join('')}
                                </span>
                            </div>
                        ` : ''}
                        ${order.logistics.calculated !== undefined ? `
                            <div class="logistics-row">
                                <span class="label"><i class="fas fa-calculator"></i> 运费计算:</span>
                                <span class="value">${order.logistics.calculated ? '已使用实时距离计算' : '使用默认运费'}</span>
                            </div>
                        ` : ''}
                        ${order.logistics.error ? `
                            <div class="logistics-row error">
                                <span class="label"><i class="fas fa-exclamation-triangle"></i> 提示:</span>
                                <span class="value">${order.logistics.error}</span>
                            </div>
                        ` : ''}
                    </div>
                </div>
                ` : ''}
                
                <div class="detail-section">
                    <h3>商品清单</h3>
                    <div class="order-items-detail">
                        ${order.items.map(item => `
                            <div class="order-item-detail">
                                <div class="product-image">
                                    <img src="https://via.placeholder.com/80x80?text=${encodeURIComponent(item.product_name)}" 
                                         alt="${item.product_name}">
                                </div>
                                <div class="product-info">
                                    <h4>${item.product_name}</h4>
                                    <div class="product-specs">
                                        <span>数量: ${item.quantity}</span>
                                        <span>单价: ¥${item.price.toFixed(2)}</span>
                                        ${item.origin_address ? `<span style="color: #007bff;"><i class="fas fa-map-marker-alt"></i> 产地: ${item.origin_address}</span>` : ''}
                                    </div>
                                </div>
                                <div class="product-total">
                                    ¥${(item.price * item.quantity).toFixed(2)}
                                </div>
                            </div>
                        `).join('')}
                    </div>
                </div>
                
                <div class="detail-section">
                    <h3>费用明细</h3>
                    <div class="cost-breakdown">
                        <div class="cost-row">
                            <span class="label">商品总价:</span>
                            <span class="value">¥${(order.total_amount - order.shipping_fee).toFixed(2)}</span>
                        </div>
                        ${order.multi_origin_fee && order.multi_origin_fee > 0 ? `
                        <div class="cost-row">
                            <span class="label">基础运费:</span>
                            <span class="value">¥${(order.shipping_fee - order.multi_origin_fee).toFixed(2)}</span>
                        </div>
                        <div class="cost-row">
                            <span class="label">多发货地附加费:</span>
                            <span class="value">¥${order.multi_origin_fee.toFixed(2)}</span>
                        </div>
                        ` : `
                        <div class="cost-row">
                            <span class="label">运费:</span>
                            <span class="value">¥${order.shipping_fee.toFixed(2)}</span>
                        </div>
                        `}
                        ${order.discount > 0 ? `
                        <div class="cost-row">
                            <span class="label">折扣:</span>
                            <span class="value discount">-${order.discount}%</span>
                        </div>
                        ` : ''}
                        <div class="cost-row total">
                            <span class="label">订单总额:</span>
                            <span class="value">¥${order.total_amount.toFixed(2)}</span>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        modal.style.display = 'block';
        document.body.style.overflow = 'hidden';
    }

    hideOrderDetail() {
        const modal = document.getElementById('orderDetailModal');
        modal.style.display = 'none';
        document.body.style.overflow = 'auto';
    }


    async confirmDelivery(orderNumber) {
        if (confirm('确定已收到商品吗？')) {
            // 这里应该调用确认收货的API
            this.showNotification('已确认收货', 'success');
            this.loadOrders();
        }
    }

    showReviewModal(orderNumber) {
        // 获取订单信息
        const order = this.orders.find(o => o.order_number === orderNumber);
        if (!order || order.status !== 'Delivered') {
            this.showNotification('该订单无法评价', 'error');
            return;
        }
        
        // 显示评价模态框（跳转到商品详情页）
        if (order.items && order.items.length > 0) {
            const firstProductId = order.items[0].productId;
            window.location.href = `product-detail.html?id=${firstProductId}&review=true`;
        }
    }

    reorder(orderNumber) {
        // 这里可以实现再次购买的逻辑
        this.showNotification('功能开发中...', 'info');
    }

    showLoading(show) {
        const loading = document.getElementById('loadingOrders');
        const ordersList = document.getElementById('ordersList');
        
        if (show) {
            loading.style.display = 'block';
            ordersList.style.display = 'none';
        } else {
            loading.style.display = 'none';
            ordersList.style.display = 'block';
        }
    }

    showEmptyState() {
        const emptyOrders = document.getElementById('emptyOrders');
        const ordersList = document.getElementById('ordersList');
        
        emptyOrders.style.display = 'block';
        ordersList.style.display = 'none';
    }

    showNotification(message, type = 'info') {
        // 先尝试使用authManager的通知方法
        if (window.authManager && window.authManager.showNotification) {
            try {
                window.authManager.showNotification(message, type);
                return;
            } catch (error) {
                console.warn('authManager.showNotification失败，使用fallback:', error);
            }
        }
        
        // 后备方案：使用alert或console
        if (type === 'error') {
            alert('错误: ' + message);
        } else if (type === 'success') {
            alert('成功: ' + message);
        } else {
            alert(message);
        }
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    // 延迟初始化，确保所有模块都已加载
    setTimeout(() => {
        console.log('初始化订单页面...');
        
        // 检查用户认证状态
        const isAuthenticated = window.authManager ? window.authManager.isAuthenticated() : false;
        const currentUser = window.authManager ? window.authManager.getCurrentUser() : null;
        
        console.log('页面初始化 - 认证状态:', isAuthenticated);
        console.log('页面初始化 - 当前用户:', currentUser);
        
        if (!isAuthenticated) {
            console.log('用户未登录，显示登录提示');
            // 显示登录提示
            const ordersList = document.getElementById('ordersList');
            const emptyOrders = document.getElementById('emptyOrders');
            if (ordersList) ordersList.style.display = 'none';
            if (emptyOrders) {
                emptyOrders.style.display = 'block';
                emptyOrders.innerHTML = `
                    <i class="fas fa-user-lock"></i>
                    <h3>请先登录</h3>
                    <p>您需要登录后才能查看订单信息</p>
                    <button class="btn btn-primary" onclick="window.authManager.showLoginModal()">立即登录</button>
                `;
            }
            return;
        }
        
        window.ordersManager = new OrdersManager();
    }, 200);
});
